package com.hzh.util;

import com.hzh.util.HgMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class RequestUtil {
    
    public static boolean isAjax(HttpServletRequest request) {
        return "XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"));
    }
    
    public static Map<String, String> getRequestParamMap(HttpServletRequest request) {
        //获取request内所有的参数名称
        Enumeration<String> paramNames = request.getParameterNames();
        Map<String, String> paramMap = new HashMap<String, String>();
        while (paramNames.hasMoreElements()) {
            String paramName = paramNames.nextElement();
            //参数名获取单个参数,封装入Map
            paramMap.put(paramName, request.getParameter(paramName));
        }
        return paramMap;
    }
    
    public static ArrayList<HgMultipartFile> getMultipartFileList(
        HttpServletRequest request) throws Exception {
        ArrayList<HgMultipartFile>  multipartList = new ArrayList<HgMultipartFile>();
        //获取附件类请求
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        for (Iterator<String> it = multipartRequest.getFileNames(); it.hasNext();) {
            String key = (String) it.next(); 
            //获取附件信息
            MultipartFile file = multipartRequest.getFile(key);
            
            HgMultipartFile multipartFile = new HgMultipartFile();
            
            multipartFile.setKey(key);
            multipartFile.setOriginalFilename(file.getOriginalFilename());
            multipartFile.setSize(file.getSize());
            multipartFile.setBytes(file.getBytes());
            
            multipartList.add(multipartFile);
        }
        return multipartList;
    }
}
